<?php
/*+--------------------------------------------------------------------
 * 作	  者: hemm <1429655840@qq.com>
 +----------------------------------------------------------------------
 * 创建日期：2015-07-08
 +----------------------------------------------------------------------
 * 文件描述：成员管理
 +----------------------------------------------------------------------
 * 升级记录：songyb整理优化功能（2015-07-08）
 *        weilp整理用户导入及用户主键生成
 +----------------------------------------------------------------------
*/
header("Content-Type:text/html;Charset=utf-8");
class Groups_userAction extends CommonAction {
    /**
     * 成员管理
     */
	
    public function index() {
    	$model = new Groups_userModel();
   		//条件检索
		if(!empty($_REQUEST['search_keyword'])) {
			$where['groupsid|name|real_name|professional|phone|email'] = array('like', '%'.$_REQUEST['search_keyword'].'%');
		}
		//分页处理
		import('ORG.Util.Page');// 导入分页类
		$count = $model->where($where)->count();  // 查询满足要求的总记录数
		
		$p = $this->_page($model, 'id');  //分页所需信息
		$page = new Page($count, $p['listRows']);  // 实例化分页类 传入总记录数和每页显示的记录数
		
 		$data = $model->field("id,
 							   groupsid,
 		                       name,
 		                       pwd,
 		                       real_name,
 		                       get_field_dict_name('user', 'gender', gender) gender,
 		                       get_field_dict_name('groups_user', 'professional', professional) professional,
 		                       duty,
 		                       certificate_no,
 		                       phone,
 		                       email,
 		                       get_formate_time(begin_time) begin_time,
 		                       get_formate_time(end_time) end_time,
 		                       time_format(timediff(end_time, begin_time),'%H:%i:%s') used_time,
 		                       get_user_name(operator) operator,
    						   update_date")  
 					  ->where($where)
 					  ->order("`".$p['order']."` ".$p['sort'])
					  ->limit($page->firstRow.', '.$page->listRows)         
				 	  ->select();
		$this->assign('data', $data);
		$show = $page->show();	//分页显示输出
		$this->assign('show', $show);	//绑定分页显示字符串
		$this->display();
    }
    
	/**
	 * 添加成员
	 */
	public function add() {
		$this->assign('province_list', get_province_list());	//省份列表
		$this->assign('gender_list', set_field_dict_list('user', 'gender'));
		$this->assign('professional_list', set_field_dict_list('groups_user', 'professional'));
		//$this->assign('status_list', set_field_dict_list('user', 'status'));
		$this->display();
	}
	
	/**
	 * 将用户信息添加至数据库
	 */
	public function insert() {
		$data = $this->add_user($this->_request(), $msg);
		if(false !== $data) {
			$this->success($msg, __APP__.'?g=Admin&m=Groups_user&a=index');
		} else {
			$this->error($msg);
		}
	}
	
	/**
	 * 修改用户信息页面显示
	 */
	public function edit() {
		//查询当前用户信息
		$model = new Groups_userModel();
		$data = $model->where("id = '".$_REQUEST['id']."'")->find();
		if(empty($data)) {
			$this->error('未找到您要修改的用户信息！');
		}
		$this->assign('data', $data);
		//数据字典信息绑定
		$this->assign('gender_list', set_field_dict_list('user', 'gender'));
		$this->assign('professional_list', set_field_dict_list('groups_user', 'professional'));
		//$this->assign('status_list', set_field_dict_list('user', 'status'));
		$this->display();
	}
	
	/**
	 * 更新用户信息至数据库
	 */
	public function update() {
		$data = $this->update_user($this->_request(), $msg);
		if(false !== $data) {
			redirect(__APP__.'?g=Admin&m=Groups_user&a=index');
		} else {
			$this->error($msg);
		}
	}
  
    /**
     * 删除用户信息
     */
	public function delete() {
		$userIds = $this->_request('ids');
		if(false !== $this->delete_user($userIds, $msg)) {
			redirect($_SERVER['HTTP_REFERER']);
		} else {
			$this->error($msg);
		}
	}
	
	/**
	 * 添加用户【供其他模块调用】
	 */
	public function add_user($post_data, &$msg) {
		$model = new Groups_userModel();
		if(!empty($post_data['pwd'])) {
			$post_data['pwd'] = md5($post_data['pwd']);
		}
		if(false !== $model->create($post_data, 1)) {
			$insertId = $model->add();
			if(false !== $insertId) {
				$msg = '用户添加成功！';
				return $insertId;
			} else {
				$msg = '用户添加失败！';
				return false;
			}
		} else {
			$msg = '用户添加失败！'.$model->getError();
			return false;
		}
	}
	
	/**
	 * 更新用户【供其他模块调用】
	 * @param unknown $post_data
	 * @param unknown $msg
	 */
	public function update_user($post_data, &$msg) {
		$model = new Groups_userModel();
		//对密码字段作特殊处理
		if(!empty($post_data['pwd'])) {
			$post_data['pwd'] = md5($post_data['pwd']);
		} else {
			unset($post_data['pwd']);
		}
		if(false !== $model->create($post_data, 0)) {
			if(false !== $model->save()) {
				$msg = '用户修改成功！';
				return true;
			} else {
				$msg = '用户修改失败！';
				return false;
			}
		} else {
			$msg = '用户修改失败！'.$model->getError();
			return false;
		}
	}
	
	/**
	 * 删除用户【供其他模块调用】
	 * @param array $userIds
	 * @param string &$msg
	 * @return boolean
	 */
	public function delete_user($userIds, &$msg) {
		if(!empty($userIds) && is_array($userIds)) {
			$model = new Groups_userModel();
			$model->startTrans();
			$id = implode("','", $userIds);	//用','分割id数组，以便于拼装sql语句
			$id = "'".$id."'";	//拼装sql语句，结果为'firstId','secondId',…
			if(false !== $model->where("id in(".$id.")")->delete()) {
				$msg = '用户删除成功！';
				$model->commit();
				return true;
			} else {
				$msg = '用户删除失败！';
				$model->rollback();
				return false;
			}
		} else {
			$msg = '您未选中任何记录！';
			return false;
		}
	}
	
	/**
	 * 通过Validform框架实时验证【用户名】的唯一性
	 * ajaxurl指定的文件可以接收到Post过来的两个值，分别是param和name，param是该元素的值，name是该元素的name名称。可以通过区别name来把一个表单下，多个实时验证请求，都指定到同一个文件。
	 */
	public function check_username() {
		if(!empty($_REQUEST['userid'])) {
			$where['_string'] = "id <> '".$_REQUEST['userid']."'";	//此条件用于修改用户信息时用户名查重检测（查重时忽略本身的用户名）
		}
		$where['name'] = $_REQUEST['param'];
		
		$model = new Groups_userModel();
		$userid = $model->where($where)->getField('id');
		//若数据库中该用户名不存在，则该用户名可以使用
		if(empty($userid)) {
			echo 'y';	//Validform实时验证成功时只能输出'y'，其它任何字符将作为验证失败提示信息返回
		} else {
			echo '该用户名已经存在，请选择其他！';
		}
	}
	
	/**
	 * 重置密码
	 */
	public function reset_pwd() {
		$model = new Groups_userModel();
		if(false !== $model->where("id = '".$_REQUEST['userid']."'")->setField('pwd', md5('666666'))) {
			$this->ajaxReturn(null, "密码重置成功", 1);
		} else {
			$this->ajaxReturn(null, "密码重置失败", 0);
		}
	}
	/*
 *	 * 导入界面
	 * 
	 * */
	public function import() {
		$head_array = C('PLDR_GROUPS_USER_EXCEL_HEAD');
		$this->assign('head_string', implode(',', $head_array));
		$this->display();
	}
	
	//用户导入（操作）
	public function importDo() {
		$model = new Groups_userModel();
		import("ORG.Net.UploadFile");
		if(!empty($_FILES['xls']['name'])){
			$upload = new UploadFile();// 实例化上传类
			$upload -> maxSize = -1;// 设置附件上传大小，-1无限制大小
		   	$upload -> savePath = C('PLDR_UPLOAD_PATH').$model ->getWebId().C('PLDR_AFFIX_PATH');
		  	$upload -> allowExts = C('PLDR_XLS_ALLOWEXTS');
			$upload -> saveRule = uniqid; //设置上传文件的保存规则
			if(!($info = $upload->uploadOne($_FILES['xls'], $upload->savePath))) { // 上传错误 提示错误信息
		   		$this->error('操作失败：文件上传错误！'.$upload->getErrorMsg());
			} else {
				$memory_limit = ini_get("memory_limit");
				ini_set("memory_limit ", C('MEMORY_LIMIT'));
				$file = $info[0]['savepath'].$info[0]['savename'];
				$xls_data = $this->importExecl($file);
				$data = $xls_data['data'][0]['Content'];
				
				//检测头部是否符合要求
				$count = $xls_data['data'][0]['Cols'];
			
				$head_array = C('PLDR_GROUPS_USER_EXCEL_HEAD');
				if($count != count($head_array)) {
					$this->error("表中列的个数为".$count."列,与要求的".count($head_array)."列不符，请核对后再导入,请务必保证在表格中不要使用公式和函数！");
				}
				$head_xls = $data[1];
				foreach ($head_array as $key => $row) {
					if($row != str_replace(' ', '', $head_xls[$key])) {
						$this->error("表中列名“".$head_xls[$key]."”与要求的“".$row."”不一致，请核对后再导入,请务必保证在表格中不要使用公式和函数！");
					}
				}
				array_shift($data);  //去掉头部
				$this->assign("");
 				//修改键值
				$head_xls = array_flip($head_xls);
				array_unshift($data,$head_xls);
				array_shift($data);
				$new_no = 0;
				$exits_no = 0;
				$area_code = '';
				
				//开启事务
				$model->startTrans();
				foreach ($data as $key => $row) {
					if(empty($temp_data)) {
						//$sql_data['id'] = $row[0]; 
						$sql_data['groupsid'] = $row[1];
						$sql_data['name'] = $row[2];
						$sql_data['pwd'] = md5(substr($row[3], -6));
						$sql_data['real_name'] = $row[4];
						$sql_data['gender'] = $row[5];
						$sql_data['professional'] = $row[6];
						$sql_data['duty'] = $row[7];
						$sql_data['certificate_no'] = $row[8];
						$sql_data['phone'] = $row[9];
						$sql_data['email'] = $row[10];
						$sql_data['operator'] = $model->getuserId();
						$sql_data['update_date'] = $model->getShortDate();
						if(false === $model->add($sql_data)) {
							$model->rollback();
							$this->error('导入失败1：'.$model->getDbError());
						}
						unset($sql_data);
					}
				}
				//提交事务
				$model->commit();				
				ini_set("memory_limit", $memory_limit);
				$this->success("导入成功，此次导入".($xls_data['data'][0]['Rows']-1)."条记录。",__APP__.'?g=Admin&m=Groups_user&a=index');
			}
		} else {
			$this->error("请选择您要导入的文件");
		}
	}
	
	/**
	 * 导入数据
	 * 
	 * */
	public function importExecl($file){ 
        if(!file_exists($file)){ 
            return array("error" =>0,'message'=>'file not found!');
        } 
        Vendor("PHPExcel.IOFactory"); 
        $objReader = PHPExcel_IOFactory::createReader('Excel5');
        try{
            $PHPReader = $objReader->load($file);
        }catch(Exception $e){}
        if(!isset($PHPReader)) return array("error"=>0,'message'=>'read error!');
        $allWorksheets = $PHPReader ->getAllSheets();
        $i = 0;
        foreach($allWorksheets as $objWorksheet){
            $sheetname = $objWorksheet ->getTitle();
             
            $allRow = $objWorksheet->getHighestRow();//how many rows
            
            $highestColumn = $objWorksheet->getHighestColumn();//how many columns
            
            $allColumn = PHPExcel_Cell::columnIndexFromString($highestColumn);
          
            $array[$i]["Title"] = $sheetname; 
            $array[$i]["Cols"] = $allColumn;
            $array[$i]["Rows"] = $allRow; 
            $arr = array();
            $isMergeCell = array();
            foreach ($objWorksheet->getMergeCells() as $cells) {//merge cells
                foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {
                    $isMergeCell[$cellReference] = true;
                }
            }
            for($currentRow = 1; $currentRow <= $allRow; $currentRow++){ 
                $row = array(); 
                for($currentColumn = 0; $currentColumn < $allColumn; $currentColumn++){;                
                    $cell = $objWorksheet->getCellByColumnAndRow($currentColumn, $currentRow);
                    $afCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn+1);
                    $bfCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn-1);
                    $col = PHPExcel_Cell::stringFromColumnIndex($currentColumn);
                   // echo $cell;
                    $address = $col.$currentRow;
                    $value = $objWorksheet->getCell($address)->getValue();
                    if(substr($value,0,1) == '='){
                        return array("error" =>0,'message' =>'can not use the formula!');
                        exit;
                    } 
                    if($isMergeCell[$col.$currentRow]&&$isMergeCell[$afCol.$currentRow]&&!empty($value)){
                        $temp = $value;
                    }elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$col.($currentRow-1)]&&empty($value)){
                        $value=$arr[$currentRow-1][$currentColumn];
                    }elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$bfCol.$currentRow]&&empty($value)){
                        $value=$temp;
                    }
                    $row[$currentColumn] = $value; 
                    
                } 
                $arr[$currentRow] = $row; 
            } 
            $array[$i]["Content"] = $arr; 

            $i++;
        }
        spl_autoload_register(array('Think','autoload'));//must, resolve ThinkPHP and PHPExcel conflicts
        unset($objWorksheet); 
        unset($PHPReader); 
        unset($PHPExcel); 
        unlink($file); 
        return array("error"=>1,"data"=>$array); 
    }
		  /*
		   * 生成主键字段
		   */
	   public function generate_primarykey($groups_userkey_left,&$groups_userkey_right){
		      if(!empty($groups_userkey_right)){
		       $groups_userkey_right = (int)$groups_userkey_right['id']+1;
		   		switch (strlen($groups_userkey_right)){
		   			case 1:
			   			return $groups_userkey_left.'00000'.$groups_userkey_right;
			   		case 2:
		   				return $groups_userkey_left.'0000'.$groups_userkey_right;
			   		case 3:
			   			return $groups_userkey_left.'000'.$groups_userkey_right;
			   		case 4:
			   			return $groups_userkey_left.'00'.$groups_userkey_right;
			   		case 5:
			   			return $groups_userkey_left.'0'.$groups_userkey_right;
			   		case 1:
			   			return $groups_userkey_left.$groups_userkey_right;
		   		}
		      }else{
		      	return $groups_userkey_left.'000001';
		      } 		
		   	}
}
?>